package com.mall.pay.services;

import com.mall.order.OrderCoreService;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayResultEnum;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dal.entitys.Payment;
import com.mall.pay.dal.persistence.PaymentMapper;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class PayCorServiceImpl implements PayCoreService {

    @Autowired
    PayHelper payHelper;
    @Autowired
    PaymentMapper paymentMapper;
    @Reference(timeout = 3000, check = false, retries = 0)
    OrderCoreService orderCoreService;

    /**
     *获取支付二维码
     * @param request
     * @return
     */
    @Override
    public AlipaymentResponse aliPay(PaymentRequest request) {
        AlipaymentResponse alipaymentResponse = new AlipaymentResponse();

        String qrCodeName = payHelper.test_trade_precreate(request);
        if (qrCodeName == null) {
            // 获取支付二维码失败
            alipaymentResponse.setCode(PayReturnCodeEnum.GET_CODE_FALIED.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.GET_CODE_FALIED.getMsg());
            return alipaymentResponse;
        }
        Payment payment = new Payment();
        payment.setOrderId(request.getTradeNo());
        payment.setStatus("0");

        //payment.setPayNo();
        // 获取支付二维码成功，向tb_payment中插入一条支付记录， 支付状态，支付中


        alipaymentResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
        alipaymentResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
        alipaymentResponse.setQrCode(qrCodeName);
        return alipaymentResponse;
    }

    @Override
    public AlipayQueryRetResponse queryAlipayRet(PaymentRequest request) {
        AlipayQueryRetResponse alipayQueryRetResponse = new AlipayQueryRetResponse();
        boolean result = payHelper.test_trade_query(request.getTradeNo());
        if (result) {
          // 支付成功
//           1. tb_payment 支付记录的支付状态，支付成功(支付成功时间，支付完成时间)
//           2. 修改订单状态，修改订单状态为已支付 ( 请求order-service)
            orderCoreService.updateOrder(1,request.getTradeNo());
//           3. 扣减锁定库存(遍历订单对应的每一个订单商品条目)
//           4. 返回支付成功的响应
            alipayQueryRetResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
            alipayQueryRetResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
        } else {
            alipayQueryRetResponse.setCode(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getCode());
            alipayQueryRetResponse.setMsg(PayReturnCodeEnum.PAYMENT_PROCESSOR_FAILED.getMsg());

//           1. tb_payment 支付记录的支付状态，支付失败，支付完成时间
//           2.  返回未支付的响应

        }
        return alipayQueryRetResponse;
    }
}
